package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.dto.SubjectsFilesDto;
import com.dingreading.cloud.admin.entity.Subjects;
import com.dingreading.cloud.admin.entity.SubjectsFiles;
import com.dingreading.cloud.admin.entity.table.SubjectsFilesTableDef;
import com.dingreading.cloud.admin.mapper.SubjectsFilesMapper;
import com.dingreading.cloud.admin.service.SubjectsFilesService;
import com.dingreading.cloud.admin.service.SubjectsService;
import com.dingreading.cloud.admin.util.CdnUrlUtil;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.FileViewUtil;
import com.dingreading.cloud.common.util.NepUtil;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 备课系统文件管理 服务层实现。
 *
 * @author EDY
 * @since 2025-10-22
 */
@Service
public class SubjectsFilesServiceImpl extends BaseServiceImpl<SubjectsFilesMapper, SubjectsFiles, SubjectsFilesTableDef> implements SubjectsFilesService {

    @Override
    protected SubjectsFilesTableDef getTable() {
        return SubjectsFilesTableDef.subjectsFiles;
    }

    @Resource
    private SubjectsService subjectsService;
    @Resource
    private CdnUrlUtil cdnUrlUtil;

    @Override
    public R<Object> getBySubjectId(HttpServletRequest request, String headStaffUid, String headStaffName, Long subjectId) {
        if (StringUtils.isBlank(headStaffUid))
            return R.fail("总部员工信息缺少");
        if (subjectId == null)
            return R.fail("请选择备课子分类");

        QueryWrapper wrapper = QueryWrapper.create()
                .where(table.subjectsId.eq(subjectId))
                .orderBy(table.enabled.desc(), table.showOrder.asc());

        List<SubjectsFilesDto> subjectsFiles = getMapper().selectListByQueryAs(wrapper, SubjectsFilesDto.class);
        if (CollectionUtils.isNotEmpty(subjectsFiles)) {
            for (SubjectsFilesDto subjectsFile : subjectsFiles) {
                if (StringUtils.isBlank(subjectsFile.getFileUrl())) {
                    continue;
                }
                R<String> r = cdnUrlUtil.getCdnUrl(request, subjectsFile.getFileUrl());
                if (R.isError(r))
                    return R.fail(r.getMsg());
                subjectsFile.setCdnFileUrl(r.getData());
            }
        }
        return R.ok(subjectsFiles);
    }

    @Override
    public R<Object> uploadFile(String headStaffUid, String headStaffName, Long subjectId, String name, String fileUrl, Integer fileType, Long id) {
        if (StringUtils.isBlank(headStaffUid))
            return R.fail("总部员工信息缺少");
        if (subjectId == null)
            return R.fail("请选择备课子分类");
        int viewType = FileViewUtil.getViewType(fileUrl);
        if (viewType == 0)
            return R.fail("文件的查看类型为0");

        Subjects subjects = subjectsService.getById(subjectId);
        if (subjects == null)
            return R.fail("请选择正确的备课子分类");

        String fileTypeName = getFileTypeName(fileType);

        SubjectsFiles data = null;
        if (id == null || id <= 0) {
            QueryWrapper wrapper = QueryWrapper.create()
                    .select(QueryMethods.max(table.showOrder))
                    .from(table)
                    .where(table.subjectsId.eq(subjectId));
            Integer maxShowOrder = getMapper().selectObjectByQueryAs(wrapper, Integer.class);
            maxShowOrder = NepUtil.nullToZero(maxShowOrder) + 1;

            data = new SubjectsFiles();
            data.setSubjectsId(subjectId);
            data.setShowOrder(maxShowOrder);
            data.setEnabled(1);
            data.setAddStaffUid(headStaffUid);
            data.setAddStaffName(headStaffName);
        } else {
            data = getById(id);
            if (data == null)
                return R.fail("获取备课系统文件信息失败");
        }
        data.setName(name);
        data.setFileUrl(fileUrl);
        data.setFileType(fileType);
        data.setFileTypeName(fileTypeName);
        data.setViewType(viewType);
        data.setLastStaffUid(headStaffUid);
        data.setLastStaffName(headStaffName);
        boolean ret = saveOrUpdate(data);
        return ret ? R.ok() : R.fail("备课系统文件保存失败");
    }

    @Override
    public R<Object> getBean(String headStaffUid, String headStaffName, Long id) {
        if (StringUtils.isBlank(headStaffUid))
            return R.fail("总部员工信息缺少");
        if (id == null)
            return R.fail("请选择备课系统文件");
        SubjectsFiles subjectsFiles = getById(id);
        return subjectsFiles == null ? R.failGet() : R.ok(subjectsFiles);
    }

    @Override
    public R<Object> updateEnabled(String headStaffUid, String headStaffName, Long id, Integer enabled) {
        if (StringUtils.isBlank(headStaffUid))
            return R.fail("总部员工信息缺少");
        if (id == null)
            return R.fail("请选择备课系统文件");
        boolean update = UpdateChain.of(SubjectsFiles.class)
                .set(table.enabled, enabled)
                .set(table.lastStaffUid, headStaffUid)
                .set(table.lastStaffName, headStaffName)
                .where(table.id.eq(id))
                .update();
        return update ? R.ok() : R.fail("备课系统文件启用状态更新失败");
    }

    @Override
    public R<Object> videoCopySubjectFile() {
        List<Subjects> subjectsList = subjectsService.listByVideoUrlIsNotNull();
        if (CollectionUtils.isEmpty(subjectsList)) {
            return R.fail("未查询到学科的教研视频");
        }
        ArrayList<SubjectsFiles> newFileList = new ArrayList<>();
        for (Subjects subjects : subjectsList) {
            SubjectsFiles file = new SubjectsFiles();
            file.setSubjectsId(subjects.getId());
            file.setName(subjects.getVideoName());
            file.setFileUrl(subjects.getVideoUrl());
            file.setFileType(5);
            file.setEnabled(1);
            newFileList.add(file);
        }
        saveBatch(newFileList);
        return R.ok();
    }

    @Override
    public R<Object> subjectFileSetViewType() {
        List<SubjectsFiles> list = list();
        if (CollectionUtils.isEmpty(list)) {
            return R.fail("未查询到学科文件");
        }
        for (SubjectsFiles files : list) {
            String name = getFileTypeName(files.getFileType());
            int viewType = FileViewUtil.getViewType(files.getFileUrl());
            UpdateChain.of(SubjectsFiles.class)
                    .set(table.fileTypeName, name)
                    .set(table.viewType, viewType)
                    .where(table.id.eq(files.getId()))
                    .update();
        }
        return R.ok();
    }

    @Override
    public SubjectsFiles getLtShowOrder(Long subjectsId, Integer showOrder) {
        QueryCondition condition = table.subjectsId.eq(subjectsId)
                .and(table.showOrder.lt(showOrder));
        QueryWrapper wrapper = QueryWrapper.create()
                .orderBy(table.showOrder.desc())
                .where(condition);
        List<SubjectsFiles> list = getMapper().selectListByQuery(wrapper);
        if (CollectionUtils.isNotEmpty(list))
            return list.get(0);
        return null;
    }

    @Override
    public SubjectsFiles getGtShowOrder(Long subjectsId, Integer showOrder) {
        QueryCondition condition = table.subjectsId.eq(subjectsId)
                .and(table.showOrder.gt(showOrder));
        QueryWrapper wrapper = QueryWrapper.create()
                .orderBy(table.showOrder.asc())
                .where(condition);
        List<SubjectsFiles> list = getMapper().selectListByQuery(wrapper);
        if (CollectionUtils.isNotEmpty(list))
            return list.get(0);
        return null;
    }

    @Override
    public void updateShowOrder(Long id, Integer showOrder) {
        UpdateChain.of(SubjectsFiles.class)
                .set(table.showOrder, showOrder)
                .where(table.id.eq(id))
                .update();
    }

    @Override
    public R<Object> setShowOrder() {
        UpdateChain.of(SubjectsFiles.class)
                .set(table.showOrder, 1)
                .where(table.fileType.eq(5))
                .update();
        UpdateChain.of(SubjectsFiles.class)
                .set(table.showOrder, 2)
                .where(table.fileType.eq(1))
                .update();
        UpdateChain.of(SubjectsFiles.class)
                .set(table.showOrder, 3)
                .where(table.fileType.eq(0))
                .update();
        UpdateChain.of(SubjectsFiles.class)
                .set(table.showOrder, 4)
                .where(table.fileType.eq(2))
                .update();
        UpdateChain.of(SubjectsFiles.class)
                .set(table.showOrder, 5)
                .where(table.fileType.eq(3))
                .update();
        UpdateChain.of(SubjectsFiles.class)
                .set(table.showOrder, 1)
                .where(table.fileType.eq(4))
                .update();
        return R.ok();
    }

    /**
     * 获取类型的名称
     */
    private String getFileTypeName(int type) {
        // 0.助教文案 1.阅读指南 2.资料下载 3.新书预告 4.入学测试 5.教研视频
        if (type == 0) {
            return "助教文案";
        } else if (type == 1) {
            return "阅读指南";
        } else if (type == 2) {
            return "资料下载";
        } else if (type == 3) {
            return "新书预告";
        } else if (type == 4) {
            return "入学测试";
        } else if (type == 5) {
            return "教研视频";
        }
        return "";
    }

}
